const express = require("express")
const router = express.Router()
const multer = require("multer")
const {join} = require("path")
const path = require("path")
const adminDB = require("../../../db/admin")

router.use((req,res,next)=>{
  if(!req.session.userInfo){
    return res.send({
      code:2,
      mes:"请先登录"
    })
  }
  next()
})

// 修改用户名
router.post("/altName",async(req,res)=>{
  try {
    let {name} = req.body
    let doc = await adminDB.findOne({name})
    if(doc){
      return res.send({
        code:7,
        mes:"该用户名已存在"
      })
    }
    let id = req.session.userInfo._id
    // 更新数据
    let info = await adminDB.findByIdAndUpdate(id,{
      name
    })
    // 更新session
    req.session.userInfo.name = name
    // 更新vuex
    let userInfoVuex = {
      _id:info._id,
      name:name,
      phone:info.phone,
      date:info.date,
      __v:info.__v
    }
    res.send({
      code:0,
      mes:"修改成功",
      data:userInfoVuex
    })
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常,请稍后再试"
    })
  }
})

// 修改密码
router.post("/altPass",async(req,res)=>{
  try {
    let {oldPass,pass} = req.body
    let id = req.session.userInfo._id
    let doc = await adminDB.findById(id)
    if(doc.pass !== oldPass){
      return res.send({
        code:4,
        mes:"原密码不正确"
      })
    }
    // 更新数据
    let info = await adminDB.findByIdAndUpdate(id,{
      pass
    })
    // 更新session
    req.session.userInfo.pass = pass
    // 清除session
    req.session.destroy()
    res.send({
      code:0,
      mes:"密码修改成功,请重新登录",
      data:info
    })
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常,请稍后再试"
    })
  }
})


let upload = multer({
  storage:multer.diskStorage({
    // 文件存储的目录
    destination(req,file,cb){
      cb(null,join(__dirname,"../../../static/file/phone"))
    },
    // 文件的名字
    filename(req,file,cb){
      let name = req.session.userInfo._id
      let ext = path.extname(file.originalname)
      req.coverFile = name+Date.now()+ext
      cb(null,req.coverFile)  //名字
    }
  })
}).single("file") //name名字 elemetUI默认为file


// 修改头像
router.post("/altPhone",async(req,res)=>{
  try {
    upload(req,res,async err=>{
      if(err){
        return res.send({
          code:8,
          mes:"上传失败"
        })
      }  
      let id = req.session.userInfo._id
      // 修改数据库
      await adminDB.findByIdAndUpdate(id,{
        phone:`/file/phone/${req.coverFile}`
      })
      // 更新数据
      let info = await adminDB.findById(id)
      // 更新session
      req.session.userInfo.phone = info.phone
      // 更新vuex
      let userInfoVuex = {
        _id:info._id,
        name:info.name,
        phone:info.phone,
        date:info.date,
        __v:info.__v
      }
      res.send({
        code:0,
        mes:"头像修改成功",
        data:userInfoVuex
      })
    }) 
  } catch (error) {
    res.send({
      code:5,
      mes:"服务器异常,请稍后再试"
    })
  }
})

module.exports = router